package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhHouseholdMapper;
import com.jwsoft.manager.core.dao.mapper.EdutHouseholdMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduHouseholdMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduHouseholdService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 户籍信息表服务实现类
 *
 * @author wangtao
 * @since 2022-12-02
 */
@Service
@Slf4j
public class EduHouseholdServiceImpl extends ServiceImpl<EduHouseholdMapper, EduHousehold> implements EduHouseholdService , TableService {

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EduhHouseholdMapper hHouseholdMapper;

    @Autowired
    private EdutHouseholdMapper tHouseholdMapper;

    private static final String HOUSEHOLD_TABLE = "edu_household";

    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 10000;


    @Override
    public EduHousehold getHouseholdById(String householdId) {
        return baseMapper.getHouseholdById(householdId);
    }

    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("EduHouseholdServiceImpl服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_household迁移" + count + "条数据");
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduHousehold> eduHouseholds = this.baseMapper.selectByYear(optionVO.getYear(), PAGE_SIZE);
            if (eduHouseholds.size() > 0) {
                List<EduhHousehold> hHouseholds = eduHouseholds.stream().map(eduHousehold -> {
                    EduhHousehold eduhHousehold = new EduhHousehold();
                    BeanUtils.copyProperties(eduHousehold, eduhHousehold);
                    eduhHousehold.setYear(Integer.valueOf(eduHousehold.getYear()));
                    eduhHousehold.setTaskDetailId(taskDetail.getTaskDetailId());
                    eduhHousehold.setEncryptFlag(BoolEnum.FALSE.getType());
                    eduhHousehold.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    eduhHousehold.setCleanFlag(BoolEnum.FALSE.getType());
                    return eduhHousehold;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hHouseholds, eduHouseholds.size() , optionVO);
                } catch (Exception e) {
                    log.error("edu_household迁移数据发生异常");
                    throw new RuntimeException("EduHouseholdServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private void performDataMigration(List<EduhHousehold> hHouseholds, Integer count, DataTaskDetailOptionVO optionVO) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    //1.数据迁移到历史表
                    int saveHCount = hHouseholdMapper.saveBatch(hHouseholds);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_household数据销毁成功！销毁数量：" + deleteCount);
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseholdServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhHousehold> Households =
                    this.baseMapper.selectEncryptionByYear(optionVO.getYear(), optionVO.getTaskDetailId(),PAGE_SIZE);
            for (EduhHousehold household : Households) {
                try {
                    this.encrypt(household);
                    household.setEncryptTime(new Date());
                    household.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    household.setEncryptRemarks("加密成功");
                    household.setEncryptFlag(BoolEnum.TRUE.getType());
                    hHouseholdMapper.updateById(household);
                }catch (Exception e){
                    this.decrypt(household);
                    household.setEncryptTime(new Date());
                    household.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    household.setEncryptFlag(BoolEnum.FALSE.getType());
                    household.setEncryptRemarks("加密失败"+e.getMessage());
                    hHouseholdMapper.updateById(household);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    private void encrypt(EduhHousehold household) {
        if (StringUtils.isNotBlank(household.getIdcard())){
            household.setIdcard(CommonSecureUtil.sm4Encrypt(household.getIdcard()));
        }
        if (StringUtils.isNotBlank(household.getFullName())){
            household.setFullName(CommonSecureUtil.sm4Encrypt(household.getFullName()));
        }
        if (StringUtils.isNotBlank(household.getBeforeName())){
            household.setBeforeName(CommonSecureUtil.sm4Encrypt(household.getBeforeName()));
        }
        if (StringUtils.isNotBlank(household.getAddress())){
            household.setAddress(CommonSecureUtil.sm4Encrypt(household.getAddress()));
        }
        if (StringUtils.isNotBlank(household.getHouseholdPlace())){
            household.setHouseholdPlace(CommonSecureUtil.sm4Encrypt(household.getHouseholdPlace()));
        }
        if (StringUtils.isNotBlank(household.getHouseholder())){
            household.setHouseholder(CommonSecureUtil.sm4Encrypt(household.getHouseholder()));
        }
        if (StringUtils.isNotBlank(household.getHouseholderIdcard())){
            household.setHouseholderIdcard(CommonSecureUtil.sm4Encrypt(household.getHouseholderIdcard()));
        }
    }

    private void decrypt(EduhHousehold household) {
        if (StringUtils.isNotBlank(household.getIdcard())){
            household.setIdcard(CommonSecureUtil.sm4Decrypt(household.getIdcard()));
        }
        if (StringUtils.isNotBlank(household.getFullName())){
            household.setFullName(CommonSecureUtil.sm4Decrypt(household.getFullName()));
        }
        if (StringUtils.isNotBlank(household.getBeforeName())){
            household.setBeforeName(CommonSecureUtil.sm4Decrypt(household.getBeforeName()));
        }
        if (StringUtils.isNotBlank(household.getAddress())){
            household.setAddress(CommonSecureUtil.sm4Decrypt(household.getAddress()));
        }
        if (StringUtils.isNotBlank(household.getHouseholdPlace())){
            household.setHouseholdPlace(CommonSecureUtil.sm4Decrypt(household.getHouseholdPlace()));
        }
        if (StringUtils.isNotBlank(household.getHouseholder())){
            household.setHouseholder(CommonSecureUtil.sm4Decrypt(household.getHouseholder()));
        }
        if (StringUtils.isNotBlank(household.getHouseholderIdcard())){
            household.setHouseholderIdcard(CommonSecureUtil.sm4Decrypt(household.getHouseholderIdcard()));
        }
    }

    /**
     * 户籍数据销毁规则
     * 报名报名表中学生户籍数据
     * 根据householdId来进行保存
     * @param optionVO
     * @return
     */
    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduHouseholdServiceImpl服务的dataDestruction来进行处理数据清洗");
        Boolean queryHistory =
                detailService.verifyQueryHistory(optionVO.getYear(), HOUSEHOLD_TABLE);
        List<EduhHousehold> hHouseholds = new ArrayList<>();
        if (queryHistory){
            hHouseholds = this.baseMapper.queryHistoryCleanHouseholdWithEnroll
                    (taskDetail.getYear(),taskDetail.getTaskDetailId());
        }else{
            hHouseholds = this.baseMapper.queryCleanHouseholdWithEnroll(optionVO.getYear(),taskDetail.getTaskDetailId());
        }
        Integer cleanCount = hHouseholds.size();
        if (cleanCount != 0){
            try {
                this.preformDataClean(hHouseholds,cleanCount);
            } catch (Exception e) {
                log.error("eduh_household数据清洗发生异常");
                throw new RuntimeException("EduHouseholdServiceImpl:" + e);
            }
        }
        return cleanCount;
    }

    private void preformDataClean(List<EduhHousehold> hHouseholds, Integer cleanCount) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    List<EdutHousehold> tHouseholds = hHouseholds.stream().map(item -> {
                        EdutHousehold tHousehold = new EdutHousehold();
                        BeanUtils.copyProperties(item, tHousehold);
                        tHousehold.setCleanFlag(BoolEnum.TRUE.getType());
                        return tHousehold;
                    }).collect(Collectors.toList());
                    tHouseholdMapper.saveBatch(tHouseholds);
                    Integer count = 0;
                    for (EduhHousehold hHousehold : hHouseholds) {
                        count ++;
                        hHouseholdMapper.deleteHistoryById(hHousehold.getHouseholdId());
                    }
                    if (count != cleanCount){
                        throw new AppException("要清洗的数据为："+cleanCount+",清洗的数据为："+count+"数据量不一致，请检查后重试！");
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void tempDataDestruction() {

    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hHouseholdMapper.selectCount(new QueryWrapper<EduhHousehold>().lambda().eq(EduhHousehold::getTaskDetailId, optionVO.getTaskDetailId())));
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhHousehold> hHouseholds
                    =  hHouseholdMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutHousehold> tHouseholds = hHouseholds.stream().map(eduhHouse -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhHouse.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(eduhHouse);
                }
                EdutHousehold tHousehold = new EdutHousehold();
                BeanUtils.copyProperties(eduhHouse, tHousehold);
                return tHousehold;
            }).collect(Collectors.toList());
            tHouseholdMapper.saveBatch(tHouseholds);
            currentPage ++;
        }
    }
}
